import {$APIMAP, $APIDATA} from '@/api/api.js'
import {isH5} from '@/utils/Platform.js'
import qs from 'qs';
const JSON5 = require('json5');

import { mapState, mapMutations } from 'vuex';
export default {
    computed: {
    	...mapState(['token', 'userInfo', 'characterType'])
    },
    methods: {
        ...mapMutations(['doLogin', 'commitToken']),
        throttle: function (duration = 1000) {
            if (this.__buttonLocked) {
                uni.$u.toast('请的操作太快, 请稍后再试');
                throw(new Error('等一等'))
            } else {
                this.__buttonLocked = true;
                setTimeout(() => {
                    this.__buttonLocked = false;
                }, duration);
            }
        },
        GM_showModel: function (text) {
            uni.showModal({
                title: '',
                showCancel: false,
                content: text,
            });
        },
        testPing: function (url) {
            // #ifdef MP-WEIXIN
            url = this.LocalTestServer + url;
            // #endif
            return new Promise((resolve, reject) => {
                var flag = false;
                setTimeout(() => {
                    if (!flag) {
                        global.localJSONConfigStarted = 'false';
                        console.log('测试环境JSON服务配置链接超时');
                        resolve({statusCode: 400});
                    }
                }, 1000);
                uni.request({
                    url: url,
                    success: (res) => {
                        flag = true;
                        resolve(res);
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            });
        },
        getFmtImage: function (v) {
            if (v) {
                v = v.replace('/mobile/teacher', this.WX_ASSETS)
                if (v.startsWith('/')) {
                    return this.API_PREFIX + v;
                } else {
                    return v;
                }
            }
        },
        getAndLoad: async function (name, url, arg3) {
            if ($APIMAP[name]) {
                url = $APIMAP[name] + url;
            }
            var requestMethod = url.startsWith('::POST') ? 'POST' : 'GET';
            var data = {};
            if (requestMethod === 'POST') {
                url = url.replace('::POST', '');
                data = qs.parse(url.slice(url.indexOf('?') + 1));
            }
            var requestUrl = url;
 
            if (!(url.startsWith('/static') || url.startsWith('./') || url.startsWith('http')) || !isH5) {
                requestUrl = this.API_PREFIX + url;
            }
            var isDevelopment = false;
            // #ifdef MP-WEIXIN
            isDevelopment = __wxConfig.envVersion == 'develop';
            // #endif
            // #ifdef H5
            isDevelopment = location.hostname == 'localhost';
            // #endif

            if (!global.localJSONConfigStarted && isDevelopment) {
                var result = await this.testPing('/wxAssets/wxJSON/globalConfig.json');            
                if (!result || (result && result.statusCode != 200)) {
                    global.localJSONConfigStarted = 'false';
                    console.log('测试环境JSON服务配置未启动， 配置文件服务自动跳转到正式环境');
                } else {
                    global.localJSONConfigStarted = 'true';
                    console.log('测试环境JSON服务配置是启动的， 配置文件会读本地的配置');
                }
            }
            
            if (global.localJSONConfigStarted == 'true' && isDevelopment && url.includes('wxJSON')) {
                // #ifndef MP-WEIXIN
                requestUrl = './static/configs' + url.split('wxJSON')[1];
                // #endif

                // #ifdef MP-WEIXIN
                requestUrl = this.LocalTestServer + '/wxAssets/wxJSON' + requestUrl.split('/wxJSON')[1];
                // #endif
            }

            var keys = Object.keys($APIDATA);
            var fakeKey = keys.find(key => requestUrl.includes(key));
            
            if (fakeKey) {
                setTimeout(() => {
                    if (typeof arg3 == 'function') {
                        arg3(JSON.parse(JSON.stringify($APIDATA[fakeKey])));
                    } else {
                        (arg3.success || args.complete)(JSON.parse(JSON.stringify($APIDATA[fakeKey])));
                    }
                }, 200);
                return;
            }

            if (typeof arg3 == 'function') {
                uni.request({
                    url: requestUrl,
                    header: {
                        token: this.token
                    },
                    complete: (res => {
                        if (typeof res.data == 'string') {
                            try {
                                arg3(JSON5.parse(res.data));
                            } catch (e) {
                                arg3(res.data);
                            }
                        } else {
                            arg3(res.data);
                        }
                    })
                });
            } else {
                uni.request({
                    url: requestUrl,
                    method: requestMethod,
                    data,
                    header: {
                        token: this.token
                    },
                    ...arg3
                });
            }
        },
        uploadFile: function (url, arg3) {
            uni.uploadFile({
                url: this.API_PREFIX + this.WX_ASSETS +'/api/v1/uploadImg.jsp', // 仅为示例，非真实的接口地址
                filePath: url,
                name: 'file',
                header: {
                    token: this.token
                },
                formData: {
                    user: 'test'
                },
                complete: (res) => {
                    arg3(JSON.parse(res.data))
                }
            });
        },

        doWxLogin: function (force) {
           var vm = this;
           var token = uni.getStorageSync('token');
           var openId = uni.getStorageSync('openId');

        //    if (token && vm.userInfo && !(force && vm.$API_PREFIX.includes('localhost'))) {
           if (token && !force) {
               return new Promise(resolve => {
                    vm.commitToken(token);
                   resolve({openId: openId, token, userInfo: vm.userInfo});
               });
           } else {
                // #ifdef MP-WEIXIN
                    return new Promise(resolve => {
                        uni.login({
                            provider: 'weixin',
                            success: function (res) {
                                vm.getAndLoad('获取token', vm.WX_ASSETS + '/api/v1/user/codeLogin.jsp?code=' + res.code, function (res) {
                                    if (res.code == 0) {
                                        uni.setStorageSync('token', res.data.token);
                                        uni.setStorageSync('openId', res.data.openid);
                                        vm.commitToken(res.data.token);
                                        if (res.data.user) {
                                            res.data.user.openId = res.data.openid;
                                            vm.doLogin(res.data.user);
                                        }
                                        resolve(res.data);
                                    } else {
                                        if (__wxConfig.envVersion != 'develop') {
                                            setTimeout(() => {
                                                return vm.doWxLogin(force);
                                            }, 500);
                                        }
                                    }
                                });
                            }
                        });
                    });
                // #endif
                // #ifndef MP-WEIXIN
                return new Promise(resolve => {
                    if (!openId) {
                        if (location.hostname == 'localhost') {
                           vm.getAndLoad('获取openId', '/mobile/h5/covid19/apiZzsb/wx/weChatCode.jsp?code=123456', function (res) {
                               if (res.code == 0) {
                                   uni.setStorageSync('token', res.data.token);
                                   uni.setStorageSync('openId', res.data.openid);
                                   vm.commitToken(res.data.token);
                                   if (res.data.user) {
                                       res.data.user.openId = res.data.openid;
                                       vm.doLogin(res.data.user);
                                   }
                                   resolve(res.data);
                               } else {
                                   if (__wxConfig.envVersion != 'develop') {
                                       setTimeout(() => {
                                           return vm.doWxLogin(force);
                                       }, 500);
                                   }
                               }
                           });
                        } else {
                            uni.showModal({
                                title: '提示',
                                content: '获取登录状态失败',
                                showCancel: false,
                                success: function(res2) {
                                    location.href = '/';
                                }
                            });
                        }
                    } else {
                        resolve({"session_key":"fyIpbSjbqpxFni9FPlYSgA==", "openId": openId, "success":false,"msg":""});
                    }
                });
                // #endif
            }
            
        },


        changeNavbarColor: function () {
            if (!this.characterType) {
                setTimeout(() => {
                    this.changeNavbarColor();
                }, 1000);
            } else {
                if (this.characterType == 1) {
                    uni.setNavigationBarColor({
                        frontColor: '#ffffff',
                        backgroundColor: '#FF8800',
                    });
                } else if (this.characterType == 2) {
                    uni.setNavigationBarColor({
                        frontColor: '#ffffff',
                        backgroundColor: '#5BC68D',
                    });
                }
            }
        }
    }
}